<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>原生js实现路由</h2>

      <!-- 1. 需要有几个可以改变url的标签 -->
      <p>
        <a href="#movies">电影</a> | <a href="#videos">视频</a> |
        <a href="#mine">我的</a>
      </p>

      <!-- 2. 需要一个可以存放切换内容的容器 -->
      <div id="box"></div>
    </div>

    <script>
      // 3. 需要一个路由表的(是一个包含path和template的对象组成的数组)
      const routes = [
        {
          path: "movies",
          template: "<div>这是电影页面</div>",
        },
        {
          path: "videos",
          template: "<div>这是视频页面</div>",
        },
        {
          path: "mine",
          template: "<div>这是我的页面</div>",
        },
      ];

      // 4. 监听hash的变化
      window.addEventListener("hashchange", () => {
        // console.log("hash值改变了", location);
        const { hash } = location;
        const str = hash.slice(1);

        routes.forEach((item) => {
          if (item.path === str) {
            document.querySelector("#box").innerHTML = item.template;
          }
        });
      });
    </script>
  </body>
</html>
